package edu.neu.ecommerceplatform.service.Impl;

import edu.neu.ecommerceplatform.Exception.ResourceNotFoundException;
import edu.neu.ecommerceplatform.config.JwtUtils;
import edu.neu.ecommerceplatform.dto.CreateUserRequest;
import edu.neu.ecommerceplatform.dto.LoginRequest;
import edu.neu.ecommerceplatform.dto.LoginResponse;
import edu.neu.ecommerceplatform.model.User;
import edu.neu.ecommerceplatform.service.AuthService;
import edu.neu.ecommerceplatform.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AuthServiceImpl implements AuthService {

    private static final Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

    private final UserService userService;
    private final JwtUtils jwtUtils;

    @Autowired
    public AuthServiceImpl(UserService userService, JwtUtils jwtUtils) {
        this.userService = userService;
        this.jwtUtils = jwtUtils;
    }

    @Transactional
    @Override
    public LoginResponse loginByPhone(LoginRequest loginRequest) {
        String phoneNumber = loginRequest.getPhoneNumber();
        String name = loginRequest.getName();

        User user = null;
        try {
            user = userService.getUserByPhone(phoneNumber);
        } catch (ResourceNotFoundException e) {
            logger.info("User with phone {} not found, checking for registration.", phoneNumber);
            if (name == null || name.trim().isEmpty()) {
                logger.warn("Registration attempt without name for phone {}.", phoneNumber);
                throw e; 
            }
        }

        if (user == null) {
            logger.info("Registering new user with phone {} and name {}.", phoneNumber, name);
            CreateUserRequest createUserRequest = new CreateUserRequest();
            createUserRequest.setPhoneNumber(phoneNumber);
            createUserRequest.setName(name);
            user = userService.createUser(createUserRequest);
        }

        logger.info("User {} logged in successfully.", user.getName());
        String token = jwtUtils.generateToken(user);

        return new LoginResponse(token, user);
    }
} 